/*
 * <h3>Title:wheel-spring-boot-web-starter系统</h3>
 * <p>Copyright (c) 2019, wnfbx@163.com. All rights reserved.</p>
 * @author wnfbx@163.com
 */
package com.wheel.autoconfigure.web.mvc.advice;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wheel.autoconfigure.web.mvc.WheelWebMvcProperties;
import com.wheel.core.exception.GlobalAppException;
import com.wheel.core.exception.IllegalArgumentAppException;
import com.wheel.core.exception.ResultCode;
import com.wheel.core.result.Result;
import com.wheel.core.utils.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.core.annotation.Order;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.client.HttpClientErrorException;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * <dt>Description:GlobalControllerAdvice</dt>
 * <dd>全局MVC异常返回处理，返回结果无异常处理，自动扫描情况可使用@ControllerAdvice注解</dd>
 *
 * @author wnfbx@163.com
 * @version 1.0 <i>2019年6月6日 下午4:23:12</i>
 * @version 1.1 <i>2021年1月26日 下午3:47</i>
 * @since jdk1.7+
 */
@ControllerAdvice
@Order(1)
public class GlobalControllerExceptionAdvice {

    private static final Logger log = LoggerFactory.getLogger(GlobalControllerExceptionAdvice.class);

    private final MessageSource messageSource;

    private final boolean showExceptionStackTraceMessage;

    @Value("${w.spring.mvc.useMessageSource:false}")
    private boolean useMessageSource;

    public GlobalControllerExceptionAdvice(MessageSource messageSource, WheelWebMvcProperties wheelWebMvcProperties) {
        this.messageSource = messageSource;
        this.showExceptionStackTraceMessage = wheelWebMvcProperties.isShowExceptionStackTraceMessage();
        Log.registered(log, "注册新ControllerAdvice");
    }

    /**
     * <dt>Description:</dt>
     * <dd>response JSON字符串</dd>
     * <dd>author wangnaifei@163.com</dd>
     * <dd>version 1.0 <i>2019/12/11 10:54</i></dd>
     *
     * @param response 响应对象
     * @param object   响应内容
     */
    private static void responseJSON(HttpServletResponse response, Result<?> object) {
        response.setHeader("Content-Type", "application/json;charset=utf-8");
        try (PrintWriter writer = response.getWriter()) {
            writer.write(new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false).writeValueAsString(object));
        } catch (IOException e) {
            e.printStackTrace();
            log.error("result format error", e);
        }
    }

    /**
     * <dt>Description:</dt>
     * <dd>全局处理参数异常IllegalArgumentAppException</dd>
     * <dd>author wnfbx@163.com</dd>
     * <dd>version 1.0 <i>2019年6月6日 下午4:23:46</i></dd>
     *
     * @param e        异常实例
     * @return com.wheel.core.result.Result<?>
     */
    @ExceptionHandler(value = IllegalArgumentAppException.class)
    public Result<?> illegalArgumentExceptionHandler(IllegalArgumentAppException e) {
        return setResultMessage(e);
    }

    /**
     * <dt>Description:</dt>
     * <dd>全局处理AppException异常</dd>
     * <dd>author wnfbx@163.com</dd>
     * <dd>version 1.0 <i>2019年6月6日 下午4:24:53</i></dd>
     *
     * @param e        异常实例
     * @return com.wheel.core.result.Result<?>
     * @see GlobalAppException 自带调试消息
     */
    @ExceptionHandler(value = GlobalAppException.class)
    public Result<?> appExceptionHandler(GlobalAppException e) {
        return setResultMessage(e);
    }

    /**
     * <dt>Description:methodArgumentNotValidExceptionHandler</dt>
     * <dd>spring参数封装时验证异常</dd>
     * <dd>author: wangnaifei@163.com</dd>
     * <dd>version:1.0 <i>2020/11/9 21:33</i></dd>
     *
     * @param e        异常实例
     * @return com.wheel.core.result.Result<?>
     * @since jdk1.7+
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result<?> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        StringBuilder stringBuffer = new StringBuilder();
        for (ObjectError error : allErrors) {
            stringBuffer.append(";").append(getCode(error)).append(":").append(error.getDefaultMessage());
        }
        return setResultMessage(new GlobalAppException(ResultCode.EXCEPTION_ARGUMENT_NOT_VALID, stringBuffer.substring(1)));
    }

    private String getCode(ObjectError error) {
        String[] codes = error.getCodes();
        return codes == null ? null : codes.length > 1 ? codes[1] : codes[0];
    }

    /**
     * <dt>Description:setResultMessage</dt>
     * <dd>根据code获取消息</dd>
     * <dd>author: wnfbx@163.com</dd>
     * <dd>version:1.0 <i>2019/12/23 18:59</i></dd>
     *
     * @param globalAppException 返回异常
     * @return com.wheel.core.result.Result<?>
     * @since jdk1.7+
     */
    public Result<Object> setResultMessage(GlobalAppException globalAppException) {
        Result<Object> result = globalAppException.asResult(showExceptionStackTraceMessage);
        if (null == result.getMessage() || useMessageSource) {
            result.setMessage(messageSource.getMessage(result.getCode(), globalAppException.getMessageArgs(), LocaleContextHolder.getLocale()));
        }
        Log.error(log, result.getMessage(), globalAppException);
        Throwable cause = globalAppException;
        while (cause != null) {
            if (cause instanceof HttpClientErrorException) {
                break;
            } else {
                cause = cause.getCause();
            }
        }
        //远程请求异常是返回响应内容
        if (cause != null) {
            HttpClientErrorException httpClientErrorException = (HttpClientErrorException) cause;
            String responseBodyAsString = httpClientErrorException.getResponseBodyAsString();
            result.setData(responseBodyAsString);
        }
        result.setRequestId(MDC.get(Log.RequestId));
        return result;
    }
}
